<template>
  <div>
    <div v-show="chooseS">
      <InSearch ref="insearch" @chooseD="chooseD"></InSearch>
    </div>

    <div v-show="!chooseS">
      <el-row :gutter="10">
        <!-- 购方 -->
        <el-col :span="12">
          <Information :title="'购买方信息'" :showInfo.sync="showInfo">
            <el-form 
              ref="buyForm" 
              :model="invoiceHead" 
              label-width="55px"
              label-position="left"
            >
              <el-form-item label="名称：" prop="custName">
                <span>{{invoiceHead.custName}}</span>
              </el-form-item>
              <el-form-item label="统一社会信用代码/纳税人识别号：" prop="custTaxcode" label-width="230px">
                <span>{{invoiceHead.custTaxcode}}</span>
              </el-form-item>
              <div v-show="showInfo">
                <el-form-item label="购买方地址：" prop="custAddress" label-width="100px">
                  <span>{{invoiceHead.custAddress}}</span>
                </el-form-item>
                <el-form-item label="电话：" prop="custTelephone">
                  <span>{{invoiceHead.custTelephone}}</span>
                </el-form-item>
                <el-col :span="20">
                  <el-form-item label="购方开户银行：" prop="custBankname" label-width="110px">
                    <span>{{invoiceHead.custBankname}}</span>
                  </el-form-item>
                  <el-form-item label="银行账户：" prop="custBankaccount" label-width="90px">
                    <span>{{invoiceHead.custBankaccount}}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <div style="height: 80px; display: flex; justify-content: center;align-items: center;">
                    <el-checkbox v-model="gfBank" @change="gfBankC">是否展示</el-checkbox>
                  </div>
                </el-col>
              </div>
            </el-form>
          </Information>
        </el-col>
        <!-- 销方 -->
        <el-col :span="12">
          <Information :title="'销售方信息'" :showInfo.sync="showInfo">
            <el-form 
              ref="sellForm" 
              :model="invoiceHead" 
              label-width="55px"
              label-position="left"
            >
              <el-form-item label="名称：" prop="orgName">
                <span>{{invoiceHead.orgName}}</span>
              </el-form-item>
              <el-form-item label="统一社会信用代码/纳税人识别号：" prop="orgTaxcode" label-width="230px">
                <span>{{invoiceHead.orgTaxcode}}</span>
              </el-form-item>
              <div v-show="showInfo">
                <el-form-item label="销售方地址" prop="orgAddress" label-width="100px">
                  <span>{{invoiceHead.orgAddress}}</span>
                </el-form-item>
                <el-form-item label="电话：" prop="orgTelephone">
                  <span>{{invoiceHead.orgTelephone}}</span>
                </el-form-item>
                <el-col :span="20">
                  <el-form-item label="销方开户银行" prop="orgBankname" label-width="110px">
                    <span>{{invoiceHead.orgBankname}}</span>
                  </el-form-item>
                  <el-form-item label="银行账户：" prop="orgBankaccount" label-width="90px">
                    <span>{{invoiceHead.orgBankaccount}}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <div style="height: 80px; display: flex; justify-content: center;align-items: center;">
                    <el-checkbox v-model="xfBank" @change="xfBankC">是否展示</el-checkbox>
                  </div>
                </el-col>
              </div>
            </el-form>
          </Information>
        </el-col>

        <!-- 开票信息 -->
        <el-col :span="24">
          <el-card>
            <!-- 头部 -->
            <div class="header">
              <span class="title">开票信息</span>
              <div class="tagsC">
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='2'" effect="plain" type="primary">纸质普票</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='3'" effect="plain" type="primary">电子专票</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='1'" effect="plain" type="primary">纸质专票</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='4'" effect="plain" type="primary">电子普票</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='5'" effect="plain" type="primary">外销发票</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='I'" effect="plain" type="primary">数电纸专</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='J'" effect="plain" type="primary">数电纸普</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='K'" effect="plain" type="primary">数电专票</el-tag>
                <el-tag size="medium" v-show="invoiceHead.invoiceType=='L'" effect="plain" type="primary">数电普票</el-tag>
                <el-tag size="medium" effect="plain" type="danger">红字</el-tag>
              </div>
            </div>
            <!-- 按钮 -->
            <div class="butC">
              <div>
                <el-popconfirm
                  title="确定删除选中的开票信息吗？"
                  @confirm="toDel"
                >
                  <el-button :disabled="tableSelect.length>0 ? false:true" type="info" slot="reference">删除</el-button>
                </el-popconfirm>
                <el-switch
                  v-model="isTax"
                  active-text="含税"
                  inactive-text="不含税"
                  style="margin-left: 20px"
                >
                含税
                </el-switch>
              </div>
            </div>
            <!-- 表格 -->
            <div class="tableC">
              <el-table
                ref="multipleTable"
                :data="invoiceHead.invoiceSplitLines"
                show-summary
                :summary-method="getSummaries"
                @selection-change="hSelectChange"
                row-key="index"
              >
                <el-table-column type="selection" width="45" align="center">
                </el-table-column>
                <el-table-column label="序号" width="60" prop="docLine">
                  <!-- <template #default="scope">
                    {{sumTax(scope.row)}}
                  </template> -->
                </el-table-column>
                <el-table-column prop="itemName" label="项目名称" min-width="200" >
                  <template #default="{row}">
                    <div style="display: flex;">
                      <el-input v-model="row.itemName" placeholder="请输入"></el-input>
                      <!-- <el-button 
                        size="mini"
                        @click="showD(row)" 
                        icon="el-icon-more-outline"
                        style="margin-left: 5px; padding:7px 10px;"
                      ></el-button> -->
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="taxCatecode" label="税收分类编码">
                  <template #default="{row}">
                    <el-input v-model="row.taxCatecode" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="itemSpec" label="规格型号">
                  <template #default="{row}">
                    <el-input v-model="row.itemSpec" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="unitName" label="单位">
                  <template #default="{row}">
                    <el-input v-model="row.unitName" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="quantity" label="数量">
                  <template #default="{row}">
                    <el-input v-model="row.quantity" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="zamountSej" label="税额" min-width="100">
                  <template #default="{row}">
                    <el-input v-model="row.zamountSej" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <div v-if="isTax">
                  <el-table-column prop="zpriceHsj" label="单价（含税）" min-width="100">
                    <template #default="{row}">
                      <el-input v-model="row.zpriceHsj" placeholder="请输入"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column  prop="zamountHsj" label="金额（含税）" min-width="100">
                    <template #default="{row}">
                      <!-- <el-input v-model="row.zamountHsj" placeholder="请输入"></el-input> -->
                      <el-input-number 
                        v-model="row.zamountHsj" 
                        controls-position="right" 
                        :precision="2"
                      ></el-input-number>
                    </template>
                  </el-table-column>
                </div>
                <div v-if="!isTax">
                  <el-table-column prop="zpriceWsj" label="单价（不含税）" min-width="110">
                    <template #default="{row}">
                      <el-input v-model="row.zpriceWsj" placeholder="请输入"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="zamountWsj" label="金额（不含税）" min-width="110">
                    <template #default="{row}">
                      <el-input-number 
                        v-model="row.zamountWsj" 
                        controls-position="right"
                        :precision="2"
                      ></el-input-number>
                    </template>
                  </el-table-column>
                </div>
                <el-table-column prop="taxRate" label="税率/征收率" min-width="100">
                  <template #default="{row}">
                    <el-select v-model="row.taxRate">
                      <el-option
                        v-for="item in taxOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="jshj">
                <span>
                  价税合计（大写）: {{ totalPrice|toChies}}
                </span>
                <span class="jshjX">
                  价税合计（小写）: {{ totalPrice}}
                </span>
              </div>
              <el-divider></el-divider>
            </div>

            <!-- 红字信息部分 -->
            <div>
              <div class="title2">
                <span >红字发票 - 红字信息</span>
              </div>
              <el-form 
                ref="redForm" 
                :rules="rules"
                :model="invoiceHead"
                label-position="top"
              >
                <el-row :gutter="25">
                  <el-col :span="5">
                    <el-form-item label="蓝字发票代码" prop="invoiceRedFpdm">
                      <el-input v-model="invoiceHead.invoiceRedFpdm" placeholder="请输入（必填项）"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item label="蓝字发票号码" prop="invoiceRedFphm">
                      <el-input v-model="invoiceHead.invoiceRedFphm" placeholder="请输入（必填项）"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="蓝字开票日期" prop="invoiceRedKprq">
                      <el-date-picker 
                        type="date" 
                        v-model="invoiceHead.invoiceRedKprq" 
                        placeholder="选择日期（必填项）" 
                        style="width:100%"
                        value-format="yyyy-MM-dd HH:mm:ss"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item label="红字申请原因" prop="invoiceRedReqm">
                      <el-select clearable v-model="invoiceHead.invoiceRedReqm" placeholder="请选择（必填项）" style="width:100%">
                        <el-option label="购方申请" :value="'11'"></el-option>
                        <el-option label="销方申请" :value="'21'"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="红字申请单号" prop="invoiceRedXxbm">
                      <el-input v-model="invoiceHead.invoiceRedXxbm" placeholder="请输入（购方必填项）"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-card>
        </el-col>

        <!-- 备注 -->
        <el-col :span="24">
          <Information :title="'备注信息'"  :showInfo.sync="showInfo">
            <el-form 
              ref="remarkForm" 
              :model="invoiceHead" 
              label-width="60px"
            >
              <el-form-item label="备注" prop="custName">
                <el-input 
                  type="textarea"
                  v-model="invoiceHead.billRemark"
                  placeholder="如有备注，请输入"
                ></el-input>
              </el-form-item>
              <el-row :gutter="25" v-show="showInfo">
                <el-col :span="6">
                  <el-form-item label="开票人" prop="userName">
                    <el-input v-model="invoiceHead.userName" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="收款人" prop="payeeName">
                    <el-input v-model="invoiceHead.payeeName" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="复核人" prop="checkName">
                    <el-input v-model="invoiceHead.checkName" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </Information>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import InSearch from "@/components/issueInvioce/redModule/InSearch.vue";
import Information from "@/components/issueInvioce/module/Information.vue";
import {transPreview} from '@/utils'
export default {
  components: {
    InSearch,
    Information
  },
  data() {
    return {
      showInfo: false,
      chooseS: true,
      invoiceHead: {
        gfBank:'0',
        xfBank: '0',
        invoiceSplitLines: []
      },
      gfBank:false,
      xfBank:false,
      // 开票信息部分
      isTax: false, // 是否含税
      tableSelect: [], // 表格选中数据
      totalPrice: '', // 价税合计
      noTaxPrince: '', // 金额
      totalTax: '', // 税额
      taxOptions:[
        { label: '0%', value: 0},
        { label: '6%', value: 0.06},
        { label: '9%', value: 0.09},
        { label: '13%', value: 0.13},
      ],
      rules: {
        invoiceRedFphm: [
          { required: true, message: '请输入蓝字发票号码', trigger: 'blur' }
        ],
        invoiceRedKprq: [
          { required: true, type: 'date', message: '请选择蓝字开票日期', trigger: 'change' }
        ],
        invoiceRedReqm: [
          { required: true, message: '请选择红字申请原因', trigger: 'change' }
        ],
      },
    }
  },
  methods: {
    // 是否展示--购方
    gfBankC(val) {
      if(val) {
        this.invoiceHead.gfBank = '1'
      } else {
        this.invoiceHead.gfBank = '0'
      }
    },
    // 是否展示--销方
    xfBankC(val) {
      if(val) {
        this.invoiceHead.xfBank = '1'
      } else {
        this.invoiceHead.xfBank = '0'
      }
    },
    butShow(val) {
      this.chooseS = val
    },
    // 选择 红字信息
    chooseD(invoiceHead) {
      this.invoiceHead = invoiceHead
    },
    // 发票详情
    invioceDe() {
      // this.invoiceHead = {...this.invoiceHead, ...this.redForm}
      this.invoiceHead.title = transPreview(this.invoiceHead.invoiceType)
    },
    // 开票信息 部分
    // 表格选中
    hSelectChange(val) {
      this.tableSelect = val
    },
    // 计算税额 金额
    sumTax(row){
      if(this.isTax) { // 1. true含税 
        if(row.zamountHsj!=0){
          row.zamountSej = Number((row.zamountHsj*row.taxRate)/(1+Number(row.taxRate))).toFixed(2) // 税额
          row.zamountWsj = (Number(row.zamountHsj)-Number(row.zamountSej)).toFixed(2) // 金额（不含税）
          if(row.quantity!=0) {
            row.zpriceHsj = (row.zamountHsj/row.quantity).toFixed(8) // 单价（含税）
          }
        }
      } else { // 2. false不含税
        if(row.zamountWsj!=0) {
          row.zamountSej = (row.zamountWsj*row.taxRate).toFixed(2) // 税额
          row.zamountHsj = (Number(row.zamountSej)+Number(row.zamountWsj)).toFixed(2) // 金额（含税）
          if(row.quantity!=0) {
            row.zpriceWsj = (row.zamountWsj/row.quantity).toFixed(8) // 单价（不含税）
          }
        }
      }
    },
    // 删除
    toDel() {
      if(this.invoiceHead.invoiceSplitLines.length <= 1) return this.$message.error('仅剩一条开票信息，无法删除！')
      this.tableSelect.forEach(it => {
        let i = this.invoiceHead.invoiceSplitLines.findIndex(item => item.docLine == it.docLine)
        if(i != -1) this.invoiceHead.invoiceSplitLines.splice(i, 1)
      })
      this.tableSelect = []
      this.$refs.multipleTable.clearSelection();
      console.log(this.tableSelect, '选中要删除的数据1111');
      this.isTax = false
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        const values = data.map(item => Number(item[column.property]))

        if(this.isTax) { // 1. 含税
          if (column.property == 'zamountHsj' ) { // 1. 含税 
            this.TaxPrince = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else if(column.property == 'zamountSej') { // 2 .税额
            this.totalTax = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = '￥'+this.totalTax.toFixed(2)
            sums[9] = '￥'+(this.TaxPrince-this.totalTax).toFixed(2) // 3.不含税
            this.noTaxPrince = sums[9] // 3.不含税
            this.totalPrice  = this.TaxPrince.toFixed(2) // 4. 含税
          } else {
            sums[index] = '';
          }
        } else { // 2. 不含税
          if (column.property == 'zamountWsj' ) { // 1. 不含税 
            this.noTaxPrince = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else if(column.property == 'zamountSej') { // 2 .税额
            this.totalTax = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[9] = '￥'+this.noTaxPrince.toFixed(2)
            sums[index] = '￥'+this.totalTax.toFixed(2)
            this.totalPrice  = (this.noTaxPrince+this.totalTax).toFixed(2) // 3. 含税
          } else {
            sums[index] = '';
          }
        }

        
      });
      return sums;
    }
  },
  filters: { //局部过滤器
    toChies: function(amount) { //形参
      // 汉字的数字
      const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      // 基本单位
      const cnIntRadice = ["", "拾", "佰", "仟"];
      // 对应整数部分扩展单位
      const cnIntUnits = ["", "万", "亿", "兆"];
      // 对应小数部分单位
      const cnDecUnits = ["角", "分"];
      // 整数金额时后面跟的字符
      const cnInteger = "整";
      // 整型完以后的单位
      const cnIntLast = "元";
      // 最大处理的数字
      const maxNum = 9999999999999999.99;
      // 金额整数部分
      let integerNum;
      // 金额小数部分
      let decimalNum;
      // 输出的中文金额字符串
      let chineseStr = "";
      // 分离金额后用的数组，预定义
      let parts;
      if (amount === "") {
        return "";
      }
      amount = parseFloat(amount);
      if (amount >= maxNum) {
        // 超出最大处理数字
        return "";
      }
      if (amount === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      // 转换为字符串
      amount = amount.toString();
      if (amount.indexOf(".") === -1) {// 1. 不是小数
        integerNum = amount;

        decimalNum = "";
      } else { // 2. 是小数
        parts = amount.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      // 获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {// 1.正数
        let zeroCount = 0;
        const IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
          const n = integerNum.substr(i, 1);
          const p = IntLen - i - 1;
          const q = p / 4;
          const m = p % 4;
          if (n === "0") {
              zeroCount++;
          } else {
            if (zeroCount > 0) {
                chineseStr += cnNums[0];
            }
            // 归零
            zeroCount = 0;
            //alert(cnNums[parseInt(n)])
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      } else{ // 2. 负数
        integerNum = Math.abs(integerNum).toString() // 负数转正数
        let zeroCount = 0;
        const IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
          const n = integerNum.substr(i, 1);
          const p = IntLen - i - 1;
          const q = p / 4;
          const m = p % 4;
          if (n === "0") {
              zeroCount++;
          } else {
            if (zeroCount > 0) {
                chineseStr += cnNums[0];
            }
            // 归零
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        console.log(chineseStr, cnIntLast, '2负数-------------');
        chineseStr = '（负数）' + chineseStr + cnIntLast;
      }
      // 小数部分
      if (decimalNum !== "") {
        const decLen = decimalNum.length;
        for (let i = 0; i < decLen; i++) {
          const n = decimalNum.substr(i, 1);
          if (n !== "0") {
              chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr === "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum === "") {
        chineseStr += cnInteger;
      }
      return chineseStr;
    }
  },
}
</script>

<style scoped lang="scss">
  .header{
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title{
      font-size: 20px;
      font-weight: 700;
    }
    .tagsC{
      margin-left: 10px;
    }
  }
  .title2{
    font-size: 18px;
    font-weight: 700;
    margin: 30px 0 10px 0;
  }
  .butC{
    display: flex;
    justify-content: space-between;
  }
  .tableC {
    margin-top: 15px;
  }
  .jshj{
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 42px;
    line-height: 42px;
    font-weight: 600;
    font-size: 14px;

    .jshjX{
      margin-left: 50px;
    }
  }
  .drawerC{
    padding: 0 20px;
  }
  ::v-deep {
    .el-form-item--small.el-form-item{
      margin-bottom: 8px;
    }
    .el-table__footer-wrapper tbody td.el-table__cell{
      background-color: #fff;
    }
    .el-divider{
      margin: 0;
    }

    .el-input-number.is-controls-right {
      width: 100%;
      .el-input-number__decrease{
        height: 0;
      }
      .el-input-number__increase{
        height: 0;
      }
      .el-icon-arrow-up{
        font-size: 0;
      }
      .el-input__inner{
        text-align: left;
        padding-right: 15px;
      }
    }
  }
</style>